﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.Tool.Forms;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;

namespace ERP_RORZE_TOOL.Tool.UserControls
{
	public partial class ucJustNew : DevExpress.XtraEditors.XtraUserControl
	{
		private int index = 0;
	    private int dateRange = 1;
		public int _action = 1;
        private bool splitBorrow = false;

        JustNewHelper helper=new JustNewHelper(new JustNew());
        public GridView GridView;
        DXPopupMenu menu;

		#region Handle Methods

		public ucJustNew()
		{

            InitializeComponent();
		    InitDateRangeMenu();
            BindDatatoGrid(dateRange);
            gridView1.BestFitColumns();
            splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;

            this.dropbtDateRange.DropDownControl = menu;
		    this.dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.SixMonths;
		}

		private void btAddNew_Click_1(object sender, EventArgs e)
		{
			AddNew();
		}

		private void btEdit_Click_1(object sender, EventArgs e)
		{
			EditRow();
		}

		private void btDelete_Click_1(object sender, EventArgs e)
		{
			DeleteRows();
		}


		private void gridView1_CustomDrawEmptyForeground_1(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e)
		{
			if(gridView1.RowCount > 0)
				return;

			StringFormat drawFormat = new StringFormat();

			drawFormat.Alignment = drawFormat.LineAlignment = StringAlignment.Center;

			e.Graphics.DrawString("No items exist in this view", e.Appearance.Font, SystemBrushes.ControlDark, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), drawFormat);

		}

		private void gridView1_DoubleClick_1(object sender, EventArgs e)
		{
			var gridView = (GridView)sender;
			var point = gridView.GridControl.PointToClient(Control.MousePosition);

			DoDoubleClick(gridView, point);
		}


		private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddNew();
		}

		private void editToolStripMenuItem_Click(object sender, EventArgs e)
		{
			EditRow();
		}

		private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
		{
			DeleteRows();
		}
		#endregion

        //public void BindDatatoGrid()
        //{
        //    JustNewHelper helper = new JustNewHelper(new JustNew());
        //    DataTable dt = helper.GetAll();

        //    gridControl1.DataSource = dt;
        //    gridView1.BestFitColumns();
        //    this.GridView = gridView1;
        //    Utilities.GridUtil.SelectRow(gridView1, index, _action);
        //}

        public void BindDatatoGrid(int range = 1)
		{
            Cursor.Current = Cursors.WaitCursor;
			JustNewHelper helper = new JustNewHelper(new JustNew());
            DataTable dt = helper.GetAll(range);

			gridControl1.DataSource = dt;
            gridView1.BestFitColumns();
            this.GridView = gridView1;
            Utilities.GridUtil.SelectRow(gridView1, index, _action);
            Cursor.Current = Cursors.Default;
		}

        public void BindDatatoGridBorrow()
        {
            BorrowHelper helper = new BorrowHelper(new Borrow());
            DataTable dt = helper.GetAll(0);

            gridBorrow.DataSource = dt;
            gridViewBorrow.BestFitColumns();
        }

		private void DoDoubleClick(GridView v, Point p)
		{
			Cursor.Current = Cursors.WaitCursor;
			_action = 1;
			index = gridView1.FocusedRowHandle;
			var info = v.CalcHitInfo(p);
			if(info.InRow || info.InRowCell)
			{
				var row = new DataRow[gridView1.SelectedRowsCount];
				row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);
				int iD = int.Parse(row[0][ToolConstants.Entities.JustNew.FieldName.ID].ToString());
			    helper.ValueObject.ID = iD;
                helper.LoadOne();

				frm_JustNewEdit fr = new frm_JustNewEdit(this);
				fr.Id = iD;
				fr.Date = helper.ValueObject.Date;
                fr.ToolId = helper.ValueObject.ToolID;
                fr.Quantity = helper.ValueObject.Quantity;
                fr.Note = helper.ValueObject.Note;

                fr.StartPosition = FormStartPosition.CenterParent;
				fr.ShowDialog();
			}
			Cursor.Current = Cursors.Default;
		}

		private void DeleteRows()
		{
			if(gridView1.SelectedRowsCount >0)
			{
				Cursor.Current = Cursors.WaitCursor;
				var row = new DataRow[gridView1.SelectedRowsCount];
				var JustNewId = new int[gridView1.SelectedRowsCount];

				for(int i=0; i< gridView1.SelectedRowsCount; i++)
				{
					row[i]= gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
					JustNewId[i] = int.Parse(row[i][ToolConstants.Entities.JustNew.FieldName.ID].ToString());
				}


				if(MessageBox.Show(ToolConstants.Message.DeleteQuestion, ToolConstants.Form.MessageBox.Warning,
								MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
				{
					JustNewHelper helper = new JustNewHelper(new JustNew());
					for(int i = 0; i < JustNewId.Length; i++)
					{
						helper.ValueObject.ID = JustNewId[i];
						if(helper.Delete() >0)
						{
							_action = 2;
						}
						else
						{
							MessageBox.Show(ToolConstants.Message.DeleteFailed, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					}
                    BindDatatoGrid(dateRange);


				}
				Cursor.Current = Cursors.Default;
			}
			else
			{
				MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void EditRow()
		{
			if(gridView1.SelectedRowsCount >0)
			{
				Cursor.Current = Cursors.WaitCursor;
				frm_JustNewEdit fr = new frm_JustNewEdit(this);
				var row = new DataRow[gridView1.SelectedRowsCount];
				row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

				index = gridView1.FocusedRowHandle;
				_action = 1;

				int iD = int.Parse(row[0][ToolConstants.Entities.JustNew.FieldName.ID].ToString());
                helper.ValueObject.ID = iD;
                helper.LoadOne();

                fr.Id = iD;
                fr.Date = helper.ValueObject.Date;
                fr.ToolId = helper.ValueObject.ToolID;
                fr.Quantity = helper.ValueObject.Quantity;
                fr.Note = helper.ValueObject.Note;

                fr.StartPosition = FormStartPosition.CenterParent;
				fr.ShowDialog();
				Cursor.Current = Cursors.Default;

			}
			else
			{
				MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void AddNew()
		{
			Cursor.Current = Cursors.WaitCursor;
			Form fr = new frm_JustNewAdd(this);
            fr.StartPosition = FormStartPosition.CenterParent;
			fr.ShowDialog();
			Cursor.Current = Cursors.Default;
		}

        private void btRefresh_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            BindDatatoGrid();
            BindDatatoGridBorrow();
            Cursor.Current = Cursors.Default;
        }

        private void borrowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            ucBorrow borrow = new ucBorrow();
            frm_BorrowAdd fr = new frm_BorrowAdd(borrow, this, true);
            var row = new DataRow[gridView1.SelectedRowsCount];

            row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);
            string toolId = row[0][ToolConstants.Entities.JustNew.FieldName.ToolID].ToString();
            int instockAtpresent = CheckInputTool(toolId);

            fr.FromJustNew = true;
            fr.ToolId = toolId;

            if (instockAtpresent <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Borrow.ToolOutStock, ToolConstants.Form.MessageBox.Notice, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(string.Format(ToolConstants.Message.Borrow.ToolInStock, toolId, instockAtpresent.ToString()), ToolConstants.Form.MessageBox.Notice, MessageBoxButtons.OK, MessageBoxIcon.Information);
                fr.StartPosition = FormStartPosition.CenterParent;
                fr.ShowDialog();
            }

            Cursor.Current = Cursors.Default;
        }

        private int CheckInputTool(string toolId)
        {
            string fieldName = ToolConstants.StoreProcedure.FieldName.DaoCu;
            string where = ToolConstants.StoreProcedure.FieldName.ToolID + "='" + toolId + "'";
            string storedName = ToolConstants.StoreProcedure.FTonKhoTongHop;

            return Utilities.CheckInput(fieldName, storedName, where);
        }

        private void gridControl1_ProcessGridKey(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteRows();
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView1.DataRowCount > 0 && splitBorrow)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    var row = gridView1.GetFocusedDataRow();
                    string toolId = row[ToolConstants.Entities.JustNew.FieldName.ToolID].ToString();

                    gridViewBorrow.ActiveFilterString = "[ToolID] = '" + toolId + "'";
                    Cursor.Current = Cursors.Default;
                }
                catch (Exception)
                {
                    
                }

            }
        }

        private void showBorrowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (splitBorrow)
            {
                showBorrowToolStripMenuItem.CheckState = CheckState.Unchecked;
                checkboxBorrow.CheckState = CheckState.Unchecked;
                splitBorrow = false;
                ShowHideBorrowPanel(splitBorrow);
            }
            else
            {
                showBorrowToolStripMenuItem.CheckState = CheckState.Checked;
                checkboxBorrow.CheckState = CheckState.Checked;
                splitBorrow = true;
                ShowHideBorrowPanel(splitBorrow);
            }
        }

        private void gridViewBorrow_CustomDrawEmptyForeground(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e)
        {
            if (gridViewBorrow.RowCount > 0)
                return;

            StringFormat drawFormat = new StringFormat();

            drawFormat.Alignment = drawFormat.LineAlignment = StringAlignment.Center;

            e.Graphics.DrawString("No items exist in this view", e.Appearance.Font, SystemBrushes.ControlDark, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), drawFormat);

        }

        private void checkboxBorrow_CheckedChanged(object sender, EventArgs e)
        {
            if (splitBorrow)
            {
                showBorrowToolStripMenuItem.CheckState = CheckState.Unchecked;
                splitBorrow = false;
                ShowHideBorrowPanel(splitBorrow);
            }
            else
            {
                showBorrowToolStripMenuItem.CheckState = CheckState.Checked;
                splitBorrow = true;
                ShowHideBorrowPanel(splitBorrow);
            }
        }

        private void ShowHideBorrowPanel(bool isSplitBorrow)
        {
            if (isSplitBorrow)
            {
                BindDatatoGridBorrow();
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Both;
            }
            else
            {
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;
            }
        }

        private void checkboxShowFooter_CheckedChanged(object sender, EventArgs e)
        {
            if (gridView1.OptionsView.ShowFooter == true)
            {
                gridView1.OptionsView.ShowFooter = false;
                gridViewBorrow.OptionsView.ShowFooter = false;
            }
            else
            {
                gridView1.OptionsView.ShowFooter = true;
                gridViewBorrow.OptionsView.ShowFooter = true;
            }
        }
        
        private void btImport_Click_1(object sender, EventArgs e)
        {
            FileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = ToolConstants.Configuration.FilterFile.Excel;

            int rowCount = 0;

            INISettings iniSettings = new INISettings();
            string connectString = iniSettings.SQLConnectionString;
            OleDbConnection connection = new OleDbConnection();
            OleDbCommand command = null;

            // Create DbDataReader to Data Worksheet
            DbDataReader dr = null;

            // Bulk Copy to SQL Server 
            SqlBulkCopy bulkInsert = new SqlBulkCopy(connectString);

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {

                try
                {
                    string path = fileDialog.FileName;

                    // Connection String to Excel Workbook
                    string excelConnectionString =
                        string.Format(
                            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False",
                            path);

                    connection.ConnectionString = excelConnectionString;
                    connection.Open();

                    command = new OleDbCommand("select  COUNT(*) from [Sheet1$]", connection);
                    rowCount = (int)command.ExecuteScalar();

                    command = new OleDbCommand("select * from [Sheet1$]", connection);
                    dr = command.ExecuteReader();

                    bulkInsert.DestinationTableName = ToolConstants.DatabaseName + ".[dbo].[" + ToolConstants.Entities.JustNew.Name + "]";

                    SqlBulkCopyColumnMapping date = new SqlBulkCopyColumnMapping(ToolConstants.Entities.JustNew.FieldName.Date, ToolConstants.Entities.JustNew.FieldName.Date);
                    bulkInsert.ColumnMappings.Add(date);

                    SqlBulkCopyColumnMapping toolId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.JustNew.FieldName.ToolID, ToolConstants.Entities.JustNew.FieldName.ToolID);
                    bulkInsert.ColumnMappings.Add(toolId);

                    SqlBulkCopyColumnMapping quantity = new SqlBulkCopyColumnMapping(ToolConstants.Entities.JustNew.FieldName.Quantity, ToolConstants.Entities.JustNew.FieldName.Quantity);
                    bulkInsert.ColumnMappings.Add(quantity);

                    SqlBulkCopyColumnMapping note = new SqlBulkCopyColumnMapping(ToolConstants.Entities.JustNew.FieldName.Note, ToolConstants.Entities.JustNew.FieldName.Note);
                    bulkInsert.ColumnMappings.Add(note);

                    Cursor.Current = Cursors.WaitCursor;
                    bulkInsert.WriteToServer(dr);
                    Cursor.Current = Cursors.Default;

                    Utilities.CreateLogFile(ToolConstants.Configuration.LogFileName.JustNew, string.Format(ToolConstants.Message.ImportSuccessfullyLog, rowCount.ToString()));
                    DialogResult message = MessageBox.Show(string.Format(ToolConstants.Message.ImportSuccessfully, rowCount.ToString()),
                                                           ToolConstants.Form.MessageBox.Message,
                                                           MessageBoxButtons.OKCancel);
                    if (message == DialogResult.OK)
                    {
                        BindDatatoGrid();
                    }

                }
                catch (Exception exception)
                {
                    Utilities.CreateLogFile(ToolConstants.Configuration.LogFileName.JustNew, string.Format(ToolConstants.Message.ImportFailedLog, exception.Message));
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    if (connection != null && connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }

        protected virtual void InitDateRangeMenu()
        {
            menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.SixMonths, new EventHandler(OnItemClick6Months), null, null, null, null));
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.OneYear, new EventHandler(OnItemClick1Year), null, null, null, null));
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.TwoYears, new EventHandler(OnItemClick2Years), null, null, null, null));
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.AllTime, new EventHandler(OnItemClickAllTime), null, null, null, null));

        }

        void OnItemClick6Months(object sender, EventArgs e)
        {
            BindDatatoGrid(1);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.SixMonths;
        }

        void OnItemClick1Year(object sender, EventArgs e)
        {
            BindDatatoGrid(2);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.OneYear;
        }

        void OnItemClick2Years(object sender, EventArgs e)
        {
            BindDatatoGrid(3);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.TwoYears;
        }

        void OnItemClickAllTime(object sender, EventArgs e)
        {
            BindDatatoGrid(0);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.AllTime;
        }

	}
}
